/**
 * login全局守卫，验证token
 */

import router from './router';
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'; // get token from cookie
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login']

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  // 用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() 
    } else {
      // 应用页
      if(to.path.includes('/application')){
        store.commit('application/SET_APPLICATIONID',Number(to.params.appId))

        //获取下拉框应用数据
        const getAllApp = store.dispatch('application/getAllApp')
        // 根据appId获取菜单注册动态路由
        const getMenuList =  store.dispatch('permission/getMenuList', to.params.appId)
        // 数据返回正常跳转，反之拦截
    
        Promise.all([getAllApp,getMenuList])
          .then(()=>{ next()})
          .catch(()=>{
            next(false)
            NProgress.done()
            Message.error('该应用服务异常，请稍后再试')
          })
      }else{
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      // next()
      // 新增：用于保存vue实例
      //乾坤应用路由节点策略更改
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
